package com.backend.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.common.constant.RedisConstant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Collections;
import java.util.Map;

@Component
@Slf4j
public class UserStatusInterceptor implements HandlerInterceptor {
    StringRedisTemplate stringRedisTemplate;
    public UserStatusInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            log.info("无状态");
            return true;
        }
        String tokenKey = RedisConstant.LOGIN_USER_KEY + token;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(tokenKey);
        if (CollUtil.isEmpty(entries)) {
            log.info("用户信息未获取");
            return true;
        }
        int status = Integer.valueOf((String)entries.get("status"));
        if (status != 0) {
            log.info("该用户已被冻结，无法访问该请求");
            return false;
        }
        log.info("用户状态无误");
        return true;
    }
}
